//
//  TaskAlertViewController.m
//  HAODE
//
//  Created by LiYinDi on 15/12/30.
//  Copyright © 2015年 reabam.com. All rights reserved.
//

#import "TaskAlertViewController.h"
#import "TaskAlertTableViewCell.h"
#import "RDVTabBarController.h"
#import "HttpRequest.h"
#import "EGORefreshTableHeaderView.h"
@interface TaskAlertViewController ()<EGORefreshTableHeaderDelegate>
{
    NSUInteger _PageIndex;
    NSUInteger _TotalCount;
    NSUInteger _TotalPage;
    
    NSMutableArray *modelArray;
    
    EGORefreshTableHeaderView *_refreshHeaderView;
    BOOL _reloading;
    
    NSString *taskType;

}

@end

@implementation TaskAlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dispatchCornerLabel.layer.cornerRadius=7.5;
    _dispatchCornerLabel.layer.masksToBounds=YES;
    _installCornerLabel.layer.cornerRadius=7.5;
    _installCornerLabel.layer.masksToBounds=YES;
    _finishedCornerLabel.layer.cornerRadius=7.5;
    _finishedCornerLabel.layer.masksToBounds=YES;
     modelArray=[NSMutableArray array];
    
   
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _listTableView.bounds.size.height, self.view.frame.size.width, _listTableView.bounds.size.height)];
        view.delegate = self;
        [_listTableView addSubview:view];
        _refreshHeaderView = view;
    
    }
    
    //  update the last update date
    [_refreshHeaderView refreshLastUpdatedDate];
    [self setNavigation];
    [self setAutoLayout];
    taskType=@"delivery";
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
    
   }
-(void) loadMessageListNextPage:(NSUInteger)oldPageNum {
    if(oldPageNum!=0 && _TotalCount<=modelArray.count)
        return;
    if(oldPageNum == 0){
        [modelArray removeAllObjects];
        [_listTableView reloadData];
    }
    _PageIndex=oldPageNum+1;
    [self requestServiceList: _PageIndex pageSize:20];
}
-(void)requestServiceList:(NSUInteger)pageIndex pageSize:(NSUInteger)pageSize
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    NSNumber *pageSizeNumber = [NSNumber numberWithInteger:pageSize];
    NSNumber *pageIndexNumber = [NSNumber numberWithInteger:pageIndex];
    [params setObject:pageSizeNumber forKey:@"PageSize"];
    [params setObject:pageIndexNumber forKey:@"PageIndex"];
    [params setObject:taskType forKey:@"taskType"];
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"MsgCenter/TaskRemind/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        
          
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                _TotalCount=[[severDataDict.dataDict objectForKey:@"TotalCount"] integerValue];
                
                if (_TotalCount%20!=0) {
                    _TotalPage=_TotalCount/20+1;
                }
                else if (_TotalCount%20==0)
                {
                    _TotalPage=_TotalCount/20;
                }
                _dispatchCornerLabel.text=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"dcount"] intValue]];
                 _installCornerLabel.text=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"icount"] intValue]];
                 _finishedCornerLabel.text=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"fcount"] intValue]];
                if ([_dispatchCornerLabel.text intValue]==0) {
                    _dispatchCornerLabel.hidden=YES;
                }
                if ([_installCornerLabel.text intValue]==0) {
                    _installCornerLabel.hidden=YES;
                }
                if ([_finishedCornerLabel.text intValue]==0) {
                    _finishedCornerLabel.hidden=YES;
                }
                NSMutableArray *mArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                
                
                for (NSDictionary* dicc in mArray )
                {
                    TaskAlertModel *model=[TaskAlertModel dataModelWithDict:dicc];
                    [modelArray addObject:model];
                }
                
                [_listTableView reloadData];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return modelArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 104;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * const  ServiceManagementIdentifier = @"SystemNotificatioanIdentifier";
    TaskAlertTableViewCell *cell=( TaskAlertTableViewCell *)[tableView dequeueReusableCellWithIdentifier: ServiceManagementIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"TaskAlertTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model=modelArray[indexPath.row];
    
       if (indexPath.row == [modelArray count] - 1)
    {
        if (_PageIndex<=_TotalPage) {
            //  NSLog(@"###LOADING???");
            [self loadMessageListNextPage:_PageIndex];
        }
    }
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TaskAlertModel *model=modelArray[indexPath.row];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:model.trId forKey:@"trId"];
    
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"MsgCenter/TaskRemind/Read" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
     
                [modelArray removeAllObjects];
                _PageIndex=0;
                [self loadMessageListNextPage:_PageIndex];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];

}

- (IBAction)btnClick:(UIButton *)sender {
    for (int i=0; i<3; i++) {
        UIButton *btn=(UIButton *)[self.view viewWithTag:i+100];
        [btn setTitleColor:[UIColor colorWithRed:102.0f/255.0f green:102.0f/255.0f blue:102.0f/255.0f alpha:1.0] forState:UIControlStateNormal];
        
    }
     [sender setTitleColor:[UIColor colorWithRed:90.0/255.0 green:130.0/255.0 blue:26.0/255.0 alpha:1.0] forState:UIControlStateNormal];
    
    [_selectedLineLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(sender.mas_left) ;
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@2) ;
        make.centerY.equalTo(_lineLabel.mas_centerY);
    }];
    if (sender.tag==100) {
        taskType=@"delivery";
    }
    else if (sender.tag==101)
    {
        taskType=@"install";
    }
    else if (sender.tag==102)
    {
        taskType=@"finish";
    }

    [modelArray removeAllObjects];
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
}
#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    [modelArray removeAllObjects];
    _PageIndex=0;
    [self loadMessageListNextPage:_PageIndex];
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    
}

- (void)doneLoadingTableViewData{
    
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_listTableView];
    
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView==_listTableView) {
        [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView==_listTableView) {
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBarHidden=NO;
        self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel* titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,40, 23)];
    titleLabel.text=@"任务提醒";
    titleLabel.font=[UIFont systemFontOfSize: 17];
    self.navigationItem.titleView=titleLabel;
 
}
-(void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setAutoLayout
{
    
    [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        
        make.height.equalTo(@50) ;
        
        make.top.equalTo(self.view.mas_top).with.offset(64) ;
    }];
    [_lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleView.mas_left);
        make.right.equalTo(_titleView.mas_right);
        
        make.height.equalTo(@1) ;
        make.top.equalTo(_titleView.mas_bottom).with.offset(-1) ;
    }];
    
    [_selectedLineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleView.mas_left);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        make.centerY.equalTo(_lineLabel.mas_centerY);
        make.height.equalTo(@2) ;
       
//         make.top.equalTo(_titleView.mas_bottom).with.offset(-1 ) ;
    }];

    [_dispatchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleView.mas_left);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@48) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_dispatchCornerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_dispatchBtn.mas_centerX).with.offset(20);
        make.width.equalTo(@15);
        
        make.height.equalTo(@15) ;
        make.top.equalTo(_titleView.mas_top) .with.offset(6);
    }];
    [_installBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_dispatchBtn.mas_right);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@48) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_installCornerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_installBtn.mas_centerX).with.offset(20);
        make.width.equalTo(@15);
        
        make.height.equalTo(@15) ;
        make.top.equalTo(_titleView.mas_top) .with.offset(6);
    }];

    [_finishedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_installBtn.mas_right);
        make.width.equalTo(_titleView.mas_width).dividedBy(3);
        
        make.height.equalTo(@48) ;
        make.top.equalTo(_titleView.mas_top) ;
    }];
    [_finishedCornerLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_finishedBtn.mas_centerX).with.offset(20);
        make.width.equalTo(@15);
        
        make.height.equalTo(@15) ;
        make.top.equalTo(_titleView.mas_top) .with.offset(6);
    }];
    [_listTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        
        make.bottom.equalTo(self.view.mas_bottom) ;
        
        
        make.top.equalTo(_titleView.mas_bottom) ;
    }];

    
}

@end
